package com.example.base.ui.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.app.PendingIntent
import android.content.Intent
import android.content.pm.ActivityInfo
import android.graphics.ColorMatrix
import android.graphics.ColorMatrixColorFilter
import android.graphics.Paint
import android.nfc.NfcAdapter
import android.os.Bundle
import android.provider.Settings
import android.view.View
import android.view.ViewGroup
import androidx.annotation.CallSuper
import androidx.annotation.IdRes
import androidx.annotation.IntRange
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import androidx.fragment.app.commit
import com.example.base.R
import com.example.base.broadcast.Event
import com.example.base.broadcast.EventBusUtil
import com.example.base.ext.LoadingView
import com.gyf.immersionbar.ktx.immersionBar
import com.kongzue.dialogx.dialogs.WaitDialogForLoading
import com.kongzue.dialogx.interfaces.OnBackPressedListener
import com.therouter.TheRouter
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**  Activity 的基类  **/
abstract class BaseActivity<VDB : ViewDataBinding> : AppCompatActivity(),
    CoroutineScope by MainScope(), LoadingView {

    /**  ViewDataBinding 对象  **/
    protected val mBinding: VDB by lazy {
        DataBindingUtil.setContentView(this, getContentRes()) as VDB
    }

    //打印设备是否开启
    private var isDeviceServiceLogined = false

    protected var nfcAdapter: NfcAdapter? = null
    protected var pendingIntent: PendingIntent? = null

    public var cardNo = ""

    @SuppressLint("SourceLockedOrientationActivity")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
       /* val paint = Paint()
        val cm = ColorMatrix()
        cm.setSaturation(0F)
        paint.setColorFilter(ColorMatrixColorFilter(cm))
        window.decorView.setLayerType(View.LAYER_TYPE_HARDWARE, paint)*/

        TheRouter.inject(this)

        if (isLockPortrait)
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT

      //  ARouter.getInstance().inject(this)
        mBinding.lifecycleOwner = this
      /*  if (isTransparentStatusBar) {
            immersionBar {
                transparentStatusBar()
            }
        } else {
            immersionBar {
                statusBarDarkFont(true)
                barColor(R.color.black)

            }
        }*/



        if (isFitsSystemWindows) {
            immersionBar {
                fitsSystemWindows(true,R.color.white)
                statusBarDarkFont(true)
              //  statusBarAlpha(0.1f)
            }
        }

        initData(savedInstanceState)
    }

    /**  是否锁定屏幕方向为竖屏, 默认锁定  **/
    protected open val isLockPortrait: Boolean = true

    /**  是否状态栏全透明  **/
    protected open val isTransparentStatusBar: Boolean = false

    /**  是否开启状态栏深色模式  **/
    protected open val isDarkMode: Boolean = false

    /**  是否开启沉浸式模式  **/
    protected open val isFitsSystemWindows: Boolean = true


    /**  状态栏半透明的程度  **/
    @IntRange(from = 0L, to = 255L)
    protected open val statusBarAlpha: Int = 50

    /**  主布局的 ID **/
    @LayoutRes
    abstract fun getContentRes(): Int

    /**  初始化数据  **/
    open fun initData(savedInstanceState: Bundle?) {}

    /**  进度条布局  **/
    /* private val layoutProgress by lazy {
         View.inflate(this, progressRes, null)
     }*/

    /**  进度 View 的 id, 不满足界面要求时可进行自定义  **/
    protected open val progressRes = R.layout.layout_progress

    /**  decorView 的主 View  **/
    private val contentView by lazy {
        window.decorView.findViewById<View>(android.R.id.content) as ViewGroup
    }

    /**
     * 跳转 Activity 获取结果
     * @param requestCode 请求码
     */
    protected inline fun <reified T : Activity> startActivityForResult(requestCode: Int) =
        startActivityForResult(Intent(this, T::class.java), requestCode)

    /**
     * 添加一个 Fragment 到目标容器
     *
     * @param containerViewId 容器的ID
     * @param fragment        添加的 Fragment
     * @param transit         动画效果, 默认是 [FragmentTransaction.TRANSIT_NONE]
     */
    protected fun addFragment(
        @IdRes containerViewId: Int, fragment: Fragment,
        transit: Int = FragmentTransaction.TRANSIT_NONE,
    ) {
        if (fragment.isRemoving || fragment.isAdded) return

        supportFragmentManager.commit(true) {
            add(containerViewId, fragment)
            setTransition(transit)
        }
    }

    /**
     * 显示一个 fragment
     * @param fragment        显示的 Fragment
     * @param transit         动画效果, 默认是 [FragmentTransaction.TRANSIT_NONE]
     */
    protected fun showFragment(
        fragment: Fragment,
        transit: Int = FragmentTransaction.TRANSIT_NONE,
    ) {
        if (fragment.isVisible) return

        supportFragmentManager.commit(true) {
            show(fragment)
            setTransition(transit)
        }
    }

    /**
     * 隐藏一个 fragment
     * @param fragment        隐藏的 Fragment
     * @param transit         动画效果, 默认是 [FragmentTransaction.TRANSIT_NONE]
     */
    protected fun hideFragment(
        fragment: Fragment,
        transit: Int = FragmentTransaction.TRANSIT_NONE,
    ) = supportFragmentManager.commit(true) {
        hide(fragment)
        setTransition(transit)
    }

    /**
     * 隐藏一个 fragment
     * @param fragment        隐藏的 Fragment
     * @param transit         动画效果, 默认是 [FragmentTransaction.TRANSIT_NONE]
     */
    protected fun hideAllFragment(
        vararg fragments: Fragment,
        transit: Int = FragmentTransaction.TRANSIT_NONE,
    ) = run {

        for (fragment in fragments){
            supportFragmentManager.commit(true) {
                hide(fragment)
                setTransition(transit)
            }        }

    }


    /**
     * 替换一个 Fragment 到目标容器
     *
     * @param containerViewId 容器的ID
     * @param fragment        替换的 Fragment
     * @param transit         动画效果, 默认是 [FragmentTransaction.TRANSIT_FRAGMENT_OPEN]
     */
    protected fun replaceFragment(
        @IdRes containerViewId: Int, fragment: Fragment,
        transit: Int = FragmentTransaction.TRANSIT_NONE,
    ) = supportFragmentManager.commit(true) {
        replace(containerViewId, fragment)
        setTransition(transit)
    }

    /**
     * 移除一个 Fragment
     *
     * @param fragment 目标移除的 Fragment
     * @param transit  动画效果, 默认是 [FragmentTransaction.TRANSIT_NONE]
     */
    protected fun removeFragment(
        fragment: Fragment,
        transit: Int = FragmentTransaction.TRANSIT_NONE,
    ) = supportFragmentManager.commit(true) {
        remove(fragment)
        setTransition(transit)
    }

    override fun showProgress() {
        hideProgress()
        // contentView.addView(layoutProgress)
        WaitDialogForLoading.show("加载中").onBackPressedListener = OnBackPressedListener {
            false
        }
    }

    override fun hideProgress() {
        WaitDialogForLoading.dismiss()
        //contentView.removeView(layoutProgress)
    }

    /**  当网络请求发生异常时默认处理, 移除进度条  **/
    @CallSuper
    open fun onNetError(errorMsg: String) = hideProgress()
    override fun onStart() {
        super.onStart()
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            if (isRegisterEventBus()) {
                EventBusUtil.register(this);
            }
        }
        /*if (NfcUtils.hasNfc(this)) {
            nfcAdapter = NfcAdapter.getDefaultAdapter(this)
            pendingIntent = PendingIntent.getActivity(
                this,
                0,
                Intent(this, javaClass).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
                0
            )
            // check NFC status.
            checkNfc()
            onNewIntent(intent)
        }*/
    }

    override fun onResume() {
        super.onResume()
        nfcAdapter?.enableForegroundDispatch(this, pendingIntent, null, null)
    }

    override fun onPause() {
        super.onPause()
        nfcAdapter?.disableForegroundDispatch(this)
    }

    override fun onDestroy() {
        cancel()
        mBinding.unbind()
        if (EventBus.getDefault().isRegistered(this)) {//加上判断

            if (isRegisterEventBus()) {
                EventBusUtil.unregister(this);
            }
        }
        super.onDestroy()
    }

    protected open fun checkNfc() {
        if (!nfcAdapter!!.isEnabled) {
            startActivity(Intent(Settings.ACTION_NFC_SETTINGS))
        }
    }

    /**
     * 是否注册事件分发
     *
     * @return true绑定EventBus事件分发，默认不绑定，子类需要绑定的话复写此方法返回true.
     */
    protected open fun isRegisterEventBus(): Boolean {
        return false
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun onEventBusCome(event: Event<Any>?) {
        if (event != null) {
            receiveEvent(event)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    open fun onStickyEventBusCome(event: Event<Any>?) {
        if (event != null) {
            receiveStickyEvent(event)
        }
    }

    /**
     * 接收到分发到事件
     *
     * @param event 事件
     */
    open fun receiveEvent(event: Event<Any>?) {}

    /**
     * 接受到分发的粘性事件
     *
     * @param event 粘性事件
     */
    open fun receiveStickyEvent(event: Event<Any>?) {}


}